<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
import { getCategoryList, addCategory, updateCategory } from '@/api/category'
import { ElMessage } from 'element-plus'
import { userStore } from '@/stores/loginStore'
const userInfo = userStore()
const instance = getCurrentInstance()
const goodData = ref([]) // 初始化为数组
// const selectedValue = ref(null) // 选中的值
const dialogVisible = ref(false)
const title = ref('')
const fromData = ref({
  id: '',
  createBy: '',
  name: '',
  parentId: '',
})
const getData = async () => {
  let result = await getCategoryList()
  const backData = result.data // 原始数据
  // 转换数据结构的函数
  const transformData = (data) => {
    return data.map(item => ({
      value: item.id,          // value 对应 id
      label: item.name,        // label 对应 name
      children: transformData(item.children) // 递归转换 children
    }))
  }
  // 转换后的数据
  const transformedData = transformData(backData)
  // 更新 goodData
  goodData.value = transformedData
}
// // 监听 selectedValue 的变化，将值赋给 categoryForm.parentId
// watch(fromData.value.selectedValue, (newValue) => {
//   categoryForm.value.parentId = newValue
//   console.log(categoryForm.value.parentId);
// })
const rules = ref({
  name: [
    { required: true, message: '商品名称不能为空', trigger: 'blur' }
  ]
})
//取消
const cancel = () => {
  dialogVisible.value = false
  fromData.value = {
    id: '',
    createBy: '',
    name: '',
    parentId: '',
  }
  instance.emit("search")
}
//提交保存
const goodFormRef = ref(null)

const goodSave = async () => {
  if (!goodFormRef) return
  await goodFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      //设置创建人
      let result = null
      fromData.value.createBy = userInfo.username
      if (fromData.value.parentId) {
        result = await updateCategory(fromData.value)
        if (result.code == 200) {
          ElMessage.success("修改成功！")
          instance.emit("search")
          dialogVisible.value = false
        } else {
          ElMessage.error("修改失败！")
        }
      } else {
        result = await addCategory(fromData.value)
        if (result.code == 200) {
          ElMessage.success("新增成功！")
          instance.emit("search")
          dialogVisible.value = false
        } else {
          ElMessage.error("新增失败！")
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
defineExpose({
  dialogVisible,
  fromData,
  title,
  getData,
})
onMounted(() => {
  getData()
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close="handleClose">
    <el-form ref="goodFormRef" :rules="rules" :model="fromData" label-width="auto" style="max-width: 600px">
      <el-form-item label="商品名字：" prop="name" style="width: 360px;">
        <el-input v-model="fromData.name" placeholder="输入商品名字" />
      </el-form-item>
      <el-form-item label="商品类别：" style="width: 360px;">
        <el-tree-select v-model="fromData.id" :data="goodData" check-strictly :render-after-expand="false" show-checkbox
          style="width: 360px" placeholder="请选择商品类别" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="goodSave"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped></style>